package com.rocketmq.entities;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author 歪大哥😁
 * @date 2019-12-21.
 */
public class Message {

    private static final int TOTAL_SIZE = 4;

    private int totalSize;

    private String body;

    public int getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(int totalSize) {
        this.totalSize = totalSize;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Message(String body) {
        this.body = body;
    }

    private Message(int totalSize, String body) {
        this.totalSize = totalSize;
        this.body = body;
    }

    public static byte[] encodeMessage(Message message) {
        byte[] body = message.body.getBytes(StandardCharsets.UTF_8);
        int totalSize = TOTAL_SIZE + body.length;
        ByteBuffer buf = ByteBuffer.allocate(totalSize);
        buf.putInt(totalSize);
        buf.put(body);
        return buf.array();
    }

    public static Message decodeMessage(byte[] message) {
        ByteBuffer buf = ByteBuffer.wrap(message);
        int totalSize = buf.getInt();
        byte[] body = new byte[totalSize - 4];
        buf.get(body, 0, totalSize - 4);
        return new Message(totalSize, new String(body, StandardCharsets.UTF_8));
    }

}
